import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression

nameList=["600188",'600348','600546','601666','601898']

def getCoef(name):
    csv_data = pd.read_csv(name+'.csv', usecols=['ret', 'risk', 'smb', 'hml'])
    csv_data = csv_data.fillna(method='ffill')
    y=csv_data['ret'].values
    x=csv_data[['risk','smb','hml']].values
    model = LinearRegression()
    model.fit(x,y)
    return model.coef_

allCoef=[]

for i in nameList:
    allCoef.append(getCoef(i))

allCoef=np.array(allCoef)

def mark(col):
    score=[2,4,6,8,10] # 和col长度相同
    sortList = sorted(enumerate(col), key=lambda x: x[1]) # 前面是原来下标，后面是原来元素值，现在的索引是顺序（从小到大）
    for i in range(len(col)):
        oldSub,_=sortList[i]
        col[oldSub]=score[i] # score里的排序和顺序一样
    return col

for i in range(3): # 3个因子
    mark(allCoef[:,i])

allScore=[]
for i in range(5): # 5个股票
    allScore.append(np.mean(allCoef[i,:]))

print(nameList)
print(allScore)